import React, {Component} from 'react';
import {Alert, StyleSheet} from 'react-native';
import {MapView} from 'react-native-amap3d';
import {getCompanyBuildingListByCity} from '~/api/company';
import store from '~/store';

class MapScreen extends Component {
    static navigationOptions = {
        title: '周边楼盘',
    };

    constructor(props) {
        super(props);
        const getters = store.getState();

        this.state = {
            pois: [],
            city_id: getters.system.city_id,
            city_name: getters.system.city,
        };

        getCompanyBuildingListByCity({
            city_id: this.state.city_id,
        }).then((r) => {
            if (r.code === 0) {
                let list = [];
                r.data.forEach((item) => {
                    list.push({
                        name: item.BuildingName,
                        location: {
                            longitude: item.Longitude,
                            latitude: item.Latitude,
                        },
                    });
                });
                if (list.length > 0) {
                    let poi = list[0];
                    this.mapView.setStatus(
                        {
                            center: {
                                longitude: poi.location.longitude,
                                latitude: poi.location.latitude,
                            },
                            zoomLevel: 13,
                        },
                        500,
                    );
                    this.setState({
                        pois: list,
                    });
                }
            } else {
                Alert.alert('获取楼盘列表失败，原因：' + r.msg);
            }
        });
    }

    goSearchPage = (keyword) => {
        this.props.navigation.push('SearchHome', {
            listtype: 1,
            CityID: this.state.city_id,
            CityName: this.state.city_name,
            keyword: keyword,
        });
    };

    render() {
        return (
            <MapView style={StyleSheet.absoluteFill} ref={(ref) => (this.mapView = ref)}>
                {this.state.pois.map((point, index) => {
                    return (
                        <MapView.Marker
                            key={index}
                            title={point.name}
                            onInfoWindowPress={() => this.goSearchPage(point.name)}
                            color="red"
                            coordinate={point.location}
                        />
                    );
                })}
            </MapView>
        );
    }
}

export default MapScreen;
